package com.baike.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.baike.bean.AliPayBaseBean;
import com.baike.bean.AlipayTradeCloseBean;
import com.baike.bean.AlipayTradeFastpayRefundQueryBean;
import com.baike.bean.AlipayTradeRefundBean;
import com.baike.config.AlipayConfig;
import com.baike.data.Result;
import com.baike.em.ConstantEnum;
import com.baike.entity.TbContent;
import com.baike.entity.TbOrder;
import com.baike.entity.Test;
import com.baike.feign.AdvertisingServiceFeign;
import com.baike.feign.OrderServiceFeign;
import com.baike.util.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("pay")
@Api(value = "广告支付接口接口")
@RefreshScope
public class AdvertisingPayController {


    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Resource
    private OrderServiceFeign orderServiceFeign;

    /**
     *
     * @param payment         付款金额*
     * @return
     * @throws AlipayApiException
     */
    //支付页面1
    //test:http://localhost:8765/pay/api/pay/alipayTradePagePay?outTradeNo=1456248303468441600&payment=233&typeId=1
    @GetMapping("alipayTradePagePay")
    @ApiOperation("支付宝支付接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "out_trade_no",value = "商品订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "payment",value = "付款金额",required = true,paramType = "query"),
            @ApiImplicitParam(name = "typeID",value = "订单类型,(1.广告订单,2课程订单,3.拼团课程调用)",required = true,paramType = "query")
    })
    public String alipayTradePagePay(@RequestParam("outTradeNo") String outTradeNo,@RequestParam("payment") String payment,
                                     @RequestParam("typeId") String typeId) throws AlipayApiException {
        //发送一条延时消息,解决用户超时未支付的问题
        rocketMQTemplate.syncSend("timeout-topic", MessageBuilder.withPayload(outTradeNo+","+typeId).build(),3000,3);


        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //订单号作为key存入redis,value为1.广告调用接口2.课程调用接口3.拼团调用接口
        //解决不同类型订单调用同一支付接口我们异步修改状态的问题
        redisTemplate.boundValueOps(outTradeNo).set(typeId);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //同步回调路径
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        //异步回调路径
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ outTradeNo +"\","
                + "\"total_amount\":\""+ payment +"\","
                + "\"subject\":\""+ outTradeNo +"\","
                + "\"body\":\""+ outTradeNo +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        //输出
        return result;
    }

    /**
     *
     * @param WIDTQout_trade_no //商户订单号，商户网站订单系统中唯一订单号
     * @param WIDTQtrade_no//支付宝交易号
     * @return
     * @throws AlipayApiException
     */
    @Resource
    private AlipayClient alipayClient;

    //交易查询
    //test:http://localhost:8765/pay/api/pay/alipayTradeQuery?out_trade_no=1454049093948133376&trade_no=2021102922001474930501570258
    @GetMapping("alipayTradeQuery")
    @ApiOperation("支付订单查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "out_trade_no",value = "订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "trade_no",value = "支付流水号",required = true,paramType = "query")
    })
    private Result alipayTradeQuery(@RequestParam("out_trade_no")String out_trade_no,@RequestParam("trade_no") String trade_no){
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","+"\"trade_no\":\""+ trade_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            AliPayBaseBean aliPayBaseBean = JSONObject.parseObject(result, AliPayBaseBean.class);
            return Result.build(ConstantEnum.SUCCESS).setResult(aliPayBaseBean);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR).setResult("支付宝交易查询失败");
        }
    }

    /**
     *
     * @param WIDTRout_trade_no//商户订单号，商户网站订单系统中唯一订单号
     * @param WIDTRtrade_no//支付宝交易号
     * @param WIDTRrefund_amount //需要退款的金额，该金额不能大于订单金额，必填
     * @param WIDTRrefund_reason//退款原因
     * @param WIDTRout_request_no  //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
     * @return
     */

    //退款
    //test:http://localhost:8765/pay/api/pay/alipayTradeRefund?WIDTRout_trade_no=1454049093948133376&WIDTRtrade_no=2021102922001474930501570258&WIDTRrefund_amount=3&WIDTRrefund_reason=rnm退钱&WIDTRout_request_no=233
    @GetMapping("alipayTradeRefunds")
    @ApiOperation("退款服务接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "WIDTRout_trade_no",value = "商户订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "WIDTRtrade_no",value = "支付宝交易号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "WIDTRrefund_amount",value = "需要退款的金额",required = true,paramType = "query"),
            @ApiImplicitParam(name = "WIDTRrefund_reason",value = "退款原因",required = true,paramType = "query"),
            @ApiImplicitParam(name = "WIDTRout_request_no",value = "退款申请号",required = true,paramType = "query")
    })
    private Result alipayTradeRefund(@RequestParam("WIDTRout_trade_no")String WIDTRout_trade_no,
                                     @RequestParam("WIDTRtrade_no")String WIDTRtrade_no,
                                     @RequestParam("WIDTRrefund_amount")String WIDTRrefund_amount,
                                     @RequestParam("WIDTRrefund_reason")String WIDTRrefund_reason,
                                     @RequestParam("WIDTRout_request_no")String WIDTRout_request_no){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDTRout_trade_no +"\","
                + "\"trade_no\":\""+ WIDTRtrade_no +"\","
                + "\"refund_amount\":\""+ WIDTRrefund_amount +"\","
                + "\"refund_reason\":\""+ WIDTRrefund_reason +"\","
                + "\"out_request_no\":\""+ WIDTRout_request_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            AlipayTradeRefundBean alipayTradeRefundBean = JSONObject.parseObject(result, AlipayTradeRefundBean.class);
            return Result.build(ConstantEnum.SUCCESS).setResult(alipayTradeRefundBean);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR).setResult("支付宝退款失败!");
        }
    }

    //根据用户id和课程id退款
    //test:http://localhost:8765/pay/api/pay/alipayTradeRefund?WIDTRout_trade_no=1454049093948133376&WIDTRtrade_no=2021102922001474930501570258&WIDTRrefund_amount=3&WIDTRrefund_reason=rnm退钱&WIDTRout_request_no=233
    @GetMapping("alipayTradeRefund")
    @ApiOperation("根据用户id和课程id退款")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentId",value = "用户id",required = true,paramType = "query"),
            @ApiImplicitParam(name = "lessonId",value = "课程id",required = true,paramType = "query")
    })
    private Result alipayTradeRefundById(@RequestParam("studentId")Long studentId,
                                     @RequestParam("lessonId")Long lessonId){
        //根据课程id,和用户id查询订单
        Result orders = orderServiceFeign.findOrderBystudentId(studentId, lessonId);
        TbOrder order = (TbOrder) orders.getResult();
        //生成退款申请号
        long id = new IdWorker().nextId();

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ order.getLessonId() +"\","
                + "\"trade_no\":\""+ order.getTradeNo() +"\","
                + "\"refund_amount\":\""+ order.getLessonPrice() +"\","
                + "\"refund_reason\":\""+ "拼团未成功!" +"\","
                + "\"out_request_no\":\""+ id+"" +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            AlipayTradeRefundBean alipayTradeRefundBean = JSONObject.parseObject(result, AlipayTradeRefundBean.class);
            return Result.build(ConstantEnum.SUCCESS).setResult(alipayTradeRefundBean);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR).setResult("支付宝退款失败!");
        }
    }






    /**
     *
     * @param WIDRQout_trade_no//商户订单号，商户网站订单系统中唯一订单号
     * @param WIDRQtrade_no//商户订单号，商户网站订单系统中唯一订单号
     * @param WIDRQout_request_no//请求退款接口时，传入的退款请求号，如果在退款请求时未传入，则该值为创建交易时的外部交易号，必填
     * @return
     */
    //退款查询
    @GetMapping("alipayTradeFastpayRefundQuery")
    @ApiOperation("退款查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "WIDRQout_trade_no",value = "商户订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "WIDRQtrade_no",value = "支付宝交易号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "WIDRQout_request_no",value = "退款请求号",required = true,paramType = "query")
    })
    private Result alipayTradeFastpayRefundQuery(String WIDRQout_trade_no,String WIDRQtrade_no,String WIDRQout_request_no){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDRQout_trade_no +"\","
                +"\"trade_no\":\""+ WIDRQtrade_no +"\","
                +"\"out_request_no\":\""+ WIDRQout_request_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            AlipayTradeFastpayRefundQueryBean bean = JSONObject.parseObject(result, AlipayTradeFastpayRefundQueryBean.class);
            return Result.build(ConstantEnum.SUCCESS).setResult(bean);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR).setResult("支付宝退款查询失败");
        }
    }

    /**
     *
     * @param WIDTCout_trade_no//商户订单号，商户网站订单系统中唯一订单号
     * @param WIDTCtrade_no //支付宝交易号
     * @return
     */
    //交易关闭
    @GetMapping("alipayTradeClose")
    @ApiOperation("交易关闭接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "WIDTCout_trade_no",value = "商户订单号",required = true,paramType = "query"),
            @ApiImplicitParam(name = "WIDTCtrade_no",value = "支付宝交易号",required = true,paramType = "query")
    })
    private Result alipayTradeClose(String WIDTCout_trade_no,String WIDTCtrade_no){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDTCout_trade_no +"\"," +"\"trade_no\":\""+ WIDTCtrade_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            AlipayTradeCloseBean alipayTradeCloseBean = JSONObject.parseObject(result, AlipayTradeCloseBean.class);
            return Result.build(ConstantEnum.SUCCESS).setResult(alipayTradeCloseBean);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR).setResult("支付宝交易关闭失败");
        }
    }
    @Resource
    private AdvertisingServiceFeign advertisingServiceFeign;
    @PostMapping("/addTest")
    public Result insertContentInfo(@RequestBody TbContent content){
//        Map<String,String> map = fileUpload(file);
//        tbContent.setUrl(map.get("fileUrl").toString());
//        tbContent.setCimage(map.get("fileUrl").toString());
        Result result = advertisingServiceFeign.insertContentInfo(content);
        return result;
    }
}
